import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/widget/tag.dart';

import '../../../constants.dart';
import '../../../models/notice_v2_list_entity.dart';
import '../../../theme.dart';
import '../../../widget/null_tip.dart';
import 'logic.dart';

class NoticePage extends StatelessWidget {
  NoticePage({Key? key}) : super(key: key);

  final logic = Get.find<NoticeLogic>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 16.w,
          ),
          onPressed: () {
            Get.back();
          },
        ),
        title: Obx(() =>
            logic.isSearching.value ? _buildSearchField() : const Text('案源')),
        actions: [
          Obx(
            () => logic.isSearching.value
                ? Container()
                : IconButton(
                    onPressed: () => {logic.onClickSearch()},
                    icon: SvgPicture.asset(
                      'assets/icons/ic_search.svg',
                      width: kIconSizeTiny,
                    ),
                  ),
          ),
          Obx(
            () => logic.isSearching.value
                ? Container()
                : IconButton(
                    onPressed: () => logic.toCreateNotice(),
                    icon: const Icon(Icons.add),
                  ),
          ),
        ],
        titleSpacing: 0,
        bottom: _buildTabBar(),
      ),
      body: Obx(() {
        if (logic.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        } else {
          return RefreshIndicator(
            onRefresh: () async => logic.reload(),
            child: Stack(
              children: [
                Padding(
                  padding: EdgeInsets.only(bottom: kSpaceSmall),
                  child: ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      controller: logic.scrollController,
                      itemBuilder: _renderRow,
                      itemCount: logic.noticeList.length + 1),
                ),
                if (logic.isSearching.value && !logic.isSearched.value)
                  Container(
                    width: double.maxFinite,
                    height: double.maxFinite,
                    color: const Color(0x55000000),
                  ),
              ],
            ),
          );
        }
      }),
    );
  }

  PreferredSizeWidget _buildTabBar() {
    return PreferredSize(
      preferredSize: Size.fromHeight(102.w),
      child: Obx(
        () => Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: TabBar(
                    labelStyle: TextStyle(
                      fontSize: kFontSizeMedium,
                      fontWeight: AppFont.fontMedium,
                      color: AppColor.colorFontBlue,
                    ),
                    controller: logic.tabController,
                    tabs: noticeIndex.values
                        .map((title) => Tab(
                            child: FittedBox(
                                fit: BoxFit.scaleDown, child: Text(title))))
                        .toList(),
                  ),
                ),
                SizedBox(width: kSpaceHuge),
                FilledButton(
                  onPressed: () => showCustomDialog(Get.context!),
                  style: ButtonStyle(
                    backgroundColor:
                        WidgetStateProperty.all(const Color(0xFFF2F3FF)),
                    padding: WidgetStateProperty.all(
                        EdgeInsets.symmetric(horizontal: kSpaceSmall)),
                    shape: WidgetStateProperty.all(
                      RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(100.w),
                      ),
                    ),
                  ),
                  child: Row(
                    children: [
                      Text(
                        '积分: ${logic.quota.value}',
                        style: TextStyle(
                          fontSize: kFontSizeSmall,
                          color: AppColor.colorFontBlue,
                        ),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        size: 16.w,
                        color: AppColor.colorIconGrey,
                      ),
                    ],
                  ),
                ),
                SizedBox(width: kSpaceMedium),
              ],
            ),
            Container(color: AppColor.colorBackground, height: kSpaceSmall),
            Container(
              color: AppColor.colorBackground,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: kSpaceMini),
                child: Row(
                  children: [
                    SizedBox(width: kSpaceMedium),
                    _buildStatusTag(0, 0 == logic.currentStatus.value),
                    SizedBox(width: 10.w),
                    _buildStatusTag(1, 1 == logic.currentStatus.value),
                    SizedBox(width: 10.w),
                    _buildStatusTag(2, 2 == logic.currentStatus.value),
                  ],
                ),
              ),
            ),
            Container(color: AppColor.colorBackground, height: kSpaceSmall),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusTag(int status, bool selected) {
    return InkWell(
      onTap: () => logic.onStatusChange(status),
      child: Tag(
        text: noticeStatus[status]!.$1,
        textColor: selected ? AppColor.colorFontBlue : AppColor.colorFontGrey,
        textSize: kFontSizeMini,
        backgroundColor: Colors.white,
        borderColor: selected ? AppColor.colorFontBlue : Colors.transparent,
        borderRadius: 50.w,
        padding: EdgeInsets.symmetric(horizontal: kSpaceMedium, vertical: 6.w),
      ),
    );
  }

  Widget _buildCaseItem(NoticeV2Data item) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            if (item.receiveUid == logic.ownerUid.value) ...[
              Tag(
                text: '我的',
                textColor: Colors.white,
                textSize: kFontSizeTiny,
                backgroundColor: AppColor.colorFontBlue,
                padding:
                    EdgeInsets.symmetric(horizontal: kSpaceTiny, vertical: 2.w),
              ),
              SizedBox(width: kSpaceTiny),
            ],
            // 案件标题
            Expanded(
              child: Text(
                item.title ?? '',
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: AppColor.colorFontBlack,
                  fontSize: kFontSizeMedium,
                  fontWeight: AppFont.fontMedium,
                ),
              ),
            ),
            // 案件标的额
            Text(
              item.subjectAmount ?? '',
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: AppColor.colorFontBlue,
                fontSize: kFontSizeMedium,
                fontWeight: AppFont.fontMedium,
              ),
            )
          ],
        ),

        SizedBox(height: kSpaceTiny),

        // 案源内容
        Text(
          item.content ?? '',
          maxLines: 3,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: AppColor.colorFontGrey,
            fontSize: kFontSizeSmall,
            fontWeight: AppFont.fontRegular,
          ),
        ),

        if (item.subjectAmount != null &&
            item.subjectAmount!.isNotEmpty &&
            item.cooperRatio != 0)
          SizedBox(height: kSpaceSmall),

        Wrap(
          spacing: kSpaceSmall,
          runSpacing: kSpaceTiny,
          children: [
            // 标的额
            item.subjectAmount.isBlank ?? true
                ? Container()
                : Container(
                    decoration: BoxDecoration(
                      color: AppColor.colorTagBackground,
                      borderRadius: BorderRadius.circular(kRadiusMini),
                    ),
                    padding: EdgeInsets.symmetric(
                        horizontal: kSpaceTiny, vertical: 2.w),
                    child: Text(
                      '标额${item.subjectAmount}',
                      style: TextStyle(
                          color: AppColor.colorFontBlack,
                          fontSize: kFontSizeMini),
                    ),
                  ),

            // 案源比例
            item.cooperRatio == 0
                ? Container()
                : Container(
                    decoration: BoxDecoration(
                      color: AppColor.colorTagBackground,
                      borderRadius: BorderRadius.circular(kRadiusMini),
                    ),
                    padding: EdgeInsets.symmetric(
                        horizontal: kSpaceTiny, vertical: 2.w),
                    child: Text(
                      '案源比例${item.cooperRatio}%',
                      style: TextStyle(
                          color: AppColor.colorFontBlack,
                          fontSize: kFontSizeMini),
                    ),
                  ),
          ],
        ),

        SizedBox(height: kSpaceMini),

        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              DateFormat('yyyy.MM.dd')
                  .format(DateTime.fromMillisecondsSinceEpoch(item.createdAt!)),
              style: TextStyle(
                color: AppColor.colorFontGrey,
                fontSize: kFontSizeMini,
                fontWeight: AppFont.fontRegular,
              ),
            ),
            Tag(
              text: switch (item.status) {
                0 => '未领取',
                1 => '已领取',
                2 => '已成交',
                int() => throw UnimplementedError(),
                null => throw UnimplementedError(),
              },
              textColor: switch (item.status) {
                0 => AppColor.colorFontOrange,
                1 => AppColor.colorFontGrey,
                2 => AppColor.colorFontGreen,
                int() => throw UnimplementedError(),
                null => throw UnimplementedError(),
              },
              textSize: kFontSizeMini,
              borderColor: switch (item.status) {
                0 => AppColor.colorFontOrange,
                1 => AppColor.colorFontGrey,
                2 => AppColor.colorFontGreen,
                int() => throw UnimplementedError(),
                null => throw UnimplementedError(),
              },
              padding:
                  EdgeInsets.symmetric(horizontal: kSpaceTiny, vertical: 2.w),
            ),
          ],
        )
      ],
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < logic.noticeList.length) {
      return Obx(
        () => Container(
          margin: EdgeInsets.symmetric(
              horizontal: kSpaceMedium, vertical: kSpaceMini),
          child: Ink(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(kRadiusSmall),
            ),
            child: InkWell(
              borderRadius: BorderRadius.circular(kRadiusSmall),
              onTap: () => logic.toNoticeDetail(index),
              child: Padding(
                padding: EdgeInsets.all(kSpaceSmall),
                child: _buildCaseItem(logic.noticeList[index]),
              ),
            ),
          ),
        ),
      );
    } else if (logic.noticeList.isEmpty) {
      return Column(
        children: [
          SizedBox(height: kSpaceHuge),
          const NullTip(),
        ],
      );
    } else {
      return _getMoreWidget();
    }
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(kSpaceMedium),
        child: Text(
          logic.bottomTips.value,
          style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
        ),
      ),
    );
  }

  Widget _buildSearchField() {
    return Container(
      height: 40.w,
      margin: EdgeInsets.only(right: kSpaceMedium),
      child: TextField(
        autofocus: true,
        controller: logic.searchController,
        keyboardType: TextInputType.text,
        textInputAction: TextInputAction.search,
        onSubmitted: (value) => logic.searchNotice(),
        decoration: InputDecoration(
          prefixIcon: IconButton(
            icon: SvgPicture.asset(
              'assets/icons/ic_search.svg',
              width: kIconSizeTiny,
              height: kIconSizeTiny,
            ),
            onPressed: () => logic.searchNotice(),
          ),
          suffixIcon: IconButton(
            iconSize: kIconSizeTiny,
            icon: const Icon(Icons.close),
            onPressed: () => logic.onCancelSearch(),
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(kRadiusMedium),
            borderSide: const BorderSide(color: AppColor.colorBorderGrey),
          ),
          hintText: '搜索案源',
          hintStyle: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontHint,
          ),
          contentPadding:
              EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
        ),
      ),
    );
  }

  void showCustomDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.transparent,
          contentPadding: EdgeInsets.zero,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15),
          ),
          content: Ink(
              decoration: BoxDecoration(
                image: const DecorationImage(
                  alignment: Alignment.topCenter,
                  image: AssetImage('assets/images/dialog_background.png'),
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Obx(
                    () => Padding(
                      padding: EdgeInsets.only(left: 20.w, top: kSpaceMini),
                      child: Text(
                        '${logic.quota.value}',
                        style: TextStyle(
                          fontSize: kFontSizeHuge,
                          fontWeight: AppFont.fontMedium,
                          color: AppColor.colorFontBlack,
                        ),
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 20.w),
                    child: Text(
                      '当前我的积分',
                      style: TextStyle(
                        fontSize: kFontSizeTiny,
                        color: AppColor.colorFontGrey,
                      ),
                    ),
                  ),
                  SizedBox(height: kSpaceSmall),
                  Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: kSpaceMedium,
                      vertical: kSpaceMini,
                    ),
                    child: Text(
                      '·每个案源可以使用积分进行领取，默认初始积分为100，领取后扣除案源所需积分',
                      style: TextStyle(
                        fontSize: kFontSizeMini,
                        color: AppColor.colorFontBlack,
                        fontWeight: AppFont.fontRegular,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: kSpaceMedium,
                      vertical: kSpaceMini,
                    ),
                    child: Text(
                      '·退回案源会返回领取案源所消耗的积分',
                      style: TextStyle(
                        fontSize: kFontSizeMini,
                        color: AppColor.colorFontBlack,
                        fontWeight: AppFont.fontRegular,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: kSpaceMedium,
                      vertical: kSpaceMini,
                    ),
                    child: Text(
                      '·案源成交后，获得双倍积分',
                      style: TextStyle(
                        fontSize: kFontSizeMini,
                        color: AppColor.colorFontBlack,
                        fontWeight: AppFont.fontRegular,
                      ),
                    ),
                  ),
                  SizedBox(height: kSpaceLarge),
                  Container(
                    height: 0.5.w,
                    width: double.infinity,
                    color: AppColor.colorLineGrey,
                  ),
                  Ink(
                    width: double.infinity,
                    decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(15),
                        bottomRight: Radius.circular(15),
                      ),
                    ),
                    child: InkWell(
                      borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(15),
                        bottomRight: Radius.circular(15),
                      ),
                      onTap: () => {Navigator.of(context).pop()},
                      child: Padding(
                        padding: EdgeInsets.symmetric(vertical: kSpaceMedium),
                        child: Text(
                          '好的',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: kFontSizeMedium,
                            color: AppColor.colorFontBlue,
                            fontWeight: AppFont.fontMedium,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              )),
        );
      },
    );
  }
}
